#include "tick.h"
#include "schedule.h"
#include "list.h"
static struct list_node g_timer_list;
extern uint32_t g_tick_cnt;
uint32_t g_tick_cnt;
void cpu_tick_handler(void)
{

    g_tick_cnt++;

}                                
uint32_t get_os_tick(void)
{
    uint64_t tick = g_tick_cnt;
    return tick;
}

void delayms_tick(uint32_t ms)
{
    struct taskTCB* task = g_osTask.taskRun;
    task->state = TASK_STATUS_SUSPEND | TASK_STATUS_DELAY;
    task->waitTime = ms + get_os_tick(); 
    schedule();
}

void add_timer(struct taskTCB* task)
{
    printf("&task->tlist=%x\n",&task->tlist);
    task->waitTime = 0;
    ListAdd(&g_timer_list,&task->tlist);
}

void remove_timer(struct taskTCB* task)
{
    ListDelete(&task->tlist);

}

int is_empty_timer(struct taskTCB* task)
{
    return ListEmpty(&task);
}

void check_timer_tick(struct taskTCB* task)
{
    int32_t current_tick = get_os_tick();
    struct list_node* node = NULL;
    struct taskTCB*   t = NULL; 
    // for(node = g_timer_list.pstNext;node !=&g_timer_list; node = node->pstNext  ){
    OS_LIST_NODE_FOR_EACH(node,((&g_timer_list)) ){
        t = LIST_NODE_ENTRY(node ,struct taskTCB,tlist );
        if (current_tick >= t->waitTime && (t->waitTime != 0)){
            scheduleInsert(t);
            break;
        }
    }
}

int osTimerTickInit(void)
{
    g_tick_cnt = 0;
    ListInit(&g_timer_list);
}


